#include "udpserver.hpp"

#include<memory>
#include<cstdio>
#include<vector>

void Usage(char* argv)
{
    std::cout << "Usage: " << argv << " port" << std::endl;
}

std::string Handle(const std::string& str)
{
    std::string ret = "Server get a message ";
    ret += str;
    return ret; 
}

bool SafeCheck(const std::string& cmd)
{
    std::vector<std::string> v = {
        "rm",
        "mv",
        "cp",
        "top"
    };
    for(auto&e : v)
    {
        auto pos = cmd.find(e);
        if(pos != std::string::npos)
        {
            return false;
        }
    } 
    return true;
}

std::string ExecuteCommand(const std::string& cmd)
{
    if(!SafeCheck(cmd))
    {
        return "unsafe";
    }
    FILE * fp = popen(cmd.c_str(),"r");
    if(fp == nullptr)
    {
        std::cout << "popen failed " << std::endl;
        return "error";
    }
    char buff[1024];
    std::string result;
    while(1)
    {
        char* ok = fgets(buff,sizeof(buff),fp);
        if(ok == nullptr)
        {
            break;
        }
        result += buff;
    }   
    

    pclose(fp);
    return result;
}


int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(port));
    svr->init();
    svr->run();


    return 0;
}